import {
  Post,
  Body,
  Controller,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Public } from 'src/common/decorators/public.decorator';
import logger from 'src/common/utils/log';
import { CreateUserDto } from '../user/dto/create-user.dto';
import { UserService } from '../user/user.service';
import { LoginUserDto, LoginUserResponseDto } from './dto/login-user.dto';
import { AuthService } from './auth.service';
import { ApiOkResponse } from '@nestjs/swagger';
import { RoleService } from '../role/role.service';
import { RoleEnum } from 'src/common/constant/enums';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly userService: UserService,
    private readonly authService: AuthService,
    private readonly roleService: RoleService,
  ) {}

  @Public()
  @Post('register')
  async register(@Body() createUserDto: CreateUserDto) {
    const user = await this.userService.register(createUserDto);
    // 默认注册的用户是普通用户
    const guestRole = await this.roleService.findByName(RoleEnum.Guest);
    await this.userService.addRole(user.id, guestRole.id);
    return this.userService.findOne(user.id);
  }
  @Public()
  @Post('login')
  @ApiOkResponse({
    description: '登录成功',
    type: [LoginUserResponseDto],
  })
  async login(
    @Body() loginUserDto: LoginUserDto,
  ): Promise<LoginUserResponseDto> {
    logger.info(`start login... ${loginUserDto.username}`);
    const user = await this.authService.validateUser(loginUserDto);
    if (!user) {
      // throw new Error('Invalid credentials');
      throw new HttpException('用户名不存在', HttpStatus.UNAUTHORIZED);
    }
    logger.info(`user exist... ${user.username}`);
    return this.authService.login(user);
  }
  @Public()
  @Post('changePassword')
  async changePassword(@Body() newPassword: LoginUserDto) {
    return this.userService.changePassword(newPassword);
  }
}
